const validate = require('../../utils/validate')
const common = require('../../utils/common')
const { shopApply } = require('../../services/stores')
const store = require('../../utils/store')
const { uploadFile } = require('../../services/upload')

Page({
  data: {
    formData: {
      shopName: '',
      address: '',
      businessTime: '',
      hasShop: '1',
      businessLicense: ""
    },
    isSubmitEnable: false,
    radioList: [
      { name: '我有门店/工作室', value: '1', checked: true },
      { name: '我没有', value: '0' },
    ],
    addressInfo: {},
    actionList: ["拍照", "从手机相册选择"],
    firstStepFormData: {},
    edit: 0,
  },
  onLoad: function ({ payload, edit }) {
    if (edit == 1) {
      this.setData({
        edit,
      })
      const payload = store.getStore('editStore')
      if (!payload) return
      this.initFormData(payload)
    }
    if (payload) {
      const firstStepFormData = JSON.parse(payload)
      this.setData({
        firstStepFormData
      })
    }
  },
  initFormData: function (payload) {
    const keys = Object.keys(this.data.formData)
    const pickForm = common.pick(payload, keys)
    pickForm.hasShop = pickForm.hasShop.toString()
    this.updateFormData(pickForm)
    const { provinceId, cityId, districtId, streetId, address, geoLat, geoLon } = payload
    const addressInfo = {
      address,
      cityId,
      districtId,
      latitude: geoLat,
      longitude: geoLon,
      provinceId,
      streetId,
    }
    this.setData({
      addressInfo
    });
  },
  checkCanSubmit: function () {
    const formData = { ...this.data.formData }
    const hasShop = formData.hasShop
    if (hasShop == '0') {
      delete formData.businessLicense
    }
    const values = Object.values(formData)
    const isSubmitEnable = values.every(v => !!v)
    this.setData({
      isSubmitEnable
    })
    return isSubmitEnable
  },
  updateFormData: function (payload) {
    this.setData({
      formData: { ...this.data.formData, ...payload }
    }, this.checkCanSubmit)
  },
  //选择省市、市辖区
  goAddressSelect: function (e) {
    wx.navigateTo({
      url: `/pages/addressSelect/index?payload=${JSON.stringify(this.data.addressInfo)}`
    });
  },
  goTimeSelect: function () {
    const timeRange = this.data.formData.businessTime.split("~")
    const start = timeRange[0] || ''
    const end = timeRange[1] || ''
    wx.navigateTo({ url: `/pages/timeRangeSelect/index?start=${start.trim()}&end=${end.trim()}` })
  },
  onFormChange: function (e) {
    const key = e.currentTarget.dataset.key
    this.updateFormData({ [key]: e.detail.value })
  },
  onTypeChange: function (e) {
    const { key, value } = e.currentTarget.dataset
    this.updateFormData({ [key]: value })
  },
  //更新门店地址
  updateAddress: function (addressInfo) {
    const { provinceName, cityName, districtName, streetName, address } = addressInfo
    const addressShow = `${provinceName}/${cityName}/${districtName}/${streetName}/${address}`
    this.setData({
      addressInfo
    });
    this.updateFormData({ address: addressShow })
  },
  // 更新营业时间
  updateTimeRange: function ({ start, end }) {
    const businessTime = `${start}~${end}`
    this.updateFormData({ businessTime })
  },
  //上传照片
  selectPhoto: function () {
    common.showActionSheet(this.data.actionList, (res) => {
      if (res.tapIndex == 0) {
        this.chooseImage('camera');
      } else if (res.tapIndex == 1) {
        this.chooseImage('album');
      }
    });
  },
  chooseImage: function (type) {
    wx.chooseImage({
      count: 1,
      sourceType: [type],
      success: res => {
        const tempFilePaths = res.tempFilePaths;
        uploadFile(tempFilePaths[0]).then((res) => {
          this.updateFormData({ businessLicense: res })
        }).catch(err => {
          common.showToast('上传失败')
        })
      },
      fail: res => {
        var canceled = res.errMsg.indexOf("cancel") != -1;
        if (!canceled) {
          common.showToast(res.errMsg);
        }
      }
    });
  },
  onConfirm: function () {
    const { provinceId, cityId, districtId, streetId, address, latitude, longitude } = this.data.addressInfo
    const addressInfo = {
      address,
      cityId,
      districtId,
      geoLat: latitude,
      geoLon: longitude,
      provinceId,
      streetId,
    }
    const allFormData = { ...this.data.firstStepFormData, ...this.data.formData, ...addressInfo }
    shopApply(allFormData).then(res => {
      wx.navigateTo({
        url: `/pages/new-store-result/index?payload=${JSON.stringify(allFormData)}`
      })
    }).catch(err => {
      common.log(err);
    })

  }
})
